package com.wjs.CarolSecKill.controller;

import com.wjs.CarolSecKill.pojo.User;
import com.wjs.CarolSecKill.service.IGoodsService;
import com.wjs.CarolSecKill.service.IUserService;
import com.wjs.CarolSecKill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IGoodsService goodsService;
    @RequestMapping("/toList")
    public String toLogin(@CookieValue("userTicket")String ticket, Model model, HttpServletRequest request, HttpServletResponse response){
        if(StringUtils.isEmpty(ticket)){
            return "login";
        }
        User user = userService.getUserByTicket(ticket, request, response);
        if(user==null){
            return "login";
        }
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        return "goodsList";
    }

    @RequestMapping("/toDetail/{id}")
    public String toDetail(@PathVariable("id") Long id,Model model,
                           @CookieValue("userTicket")String ticket,HttpServletRequest request,
                           HttpServletResponse response){
        if(StringUtils.isEmpty(ticket)){
            return "login";
        }
        User user = userService.getUserByTicket(ticket, request, response);
        if(user==null){
            return "login";
        }
        int secKillStatus=0;
        int remainSeconds=0;
        GoodsVo goodsVo = goodsService.findGoodsVoById(id);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate=new Date();
        if(nowDate.before(startDate)){
            remainSeconds=(int) ((startDate.getTime()-nowDate.getTime())/1000);
        }else if(nowDate.after(endDate)){
            //秒杀结束
            secKillStatus=2;
            remainSeconds=-1;
        }else {
            //秒杀进行中
            secKillStatus=1;
            remainSeconds=0;
        }
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("secKillStatus",secKillStatus);
        model.addAttribute("user",user);
        model.addAttribute("goods",goodsVo);
        System.out.println();
        return "goodsDetail";
    }
}
